# -*- coding: utf-8 -*-
__author__ = 'vladbranzei'

import time

import cherrypy
from cherrypy import HTTPError
from pymongo.errors import DuplicateKeyError

from onlineutils.web import validate,has_scope, jsonify
from ulise.mapper.leaderboard_mapper import LeaderboardMapper
from ulise.mapper.entries_mapper import EntriesMapper


class Ulise(object):

    @jsonify
    @validate
    @has_scope("leaderboard")
    def post(self, *kwargs):
        args = kwargs[0]
        try:
            if not args['leaderboard_name'] or not args['order'] or not args['score'] or not args['display_name']:
                cherrypy.response.status = 400
                return "Missing arguments"
            custom_fields = {}
            for item in args:
                if item[0] == "_":
                    custom_fields[item] = args[item]

            tokens = args['token'].split("|")
            credential = tokens[1]
            game = tokens[3]
            leaderboard_name = args['leaderboard_name']
            order = args['order']
            score = args['score']
            display_name = args['display_name']
            type = 'normal'

            mapper = LeaderboardMapper()
            if mapper.check(game, leaderboard_name):
                entries_mapper = EntriesMapper()
                result = entries_mapper.add_entry(mapper.foundLeaderboard.id, credential, int(score), display_name, custom_fields)
                if result == True:
                    return "Leaderboard updated"
            else:
                #create the leaderboard + a new entry collection
                result = mapper.create(game, leaderboard_name, type, order, time.time())
                if result == True:
                    entries_mapper = EntriesMapper()
                    result = entries_mapper.add_entry(mapper.foundLeaderboard.id, credential, score, display_name, custom_fields)
                    if result:
                        return "Entry added"
                    else:
                        return "Entry"

        except DuplicateKeyError as e:
            cherrypy.response.status = 500
        except KeyError as e:
            cherrypy.response.status = 400
        except HTTPError as e:
            cherrypy.response.status = e.code

    @jsonify
    @validate
    @has_scope("leaderboard")
    def get_leaderboard(self, *kwargs):
        args = kwargs[0]
        try:
            if not args['leaderboard_name'] or not args['order']:
                cherrypy.response.status = 400
                return "Missing arguments"
            else:
                game = args['token'].split("|")[3]
                leaderboard_name = args['leaderboard_name']

                offset = None
                if 'offset' in args.keys():
                    try:
                        offset = int(args['offset'])
                    except ValueError as e:
                        cherrypy.response.status = 400
                        return "Wrong arguments"
                else:
                    offset = 0

                limit = None
                if 'limit' in args.keys():
                    try:
                        limit = int(args['limit'])
                    except ValueError as e:
                        cherrypy.response.status = 400
                        return "Wrong arguments"
                else:
                    limit = 1000

                order = args['order']

                mapper = LeaderboardMapper()
                if mapper.check(game, leaderboard_name):
                    id = mapper.foundLeaderboard.id
                    entries_mapper = EntriesMapper()
                    result = entries_mapper._get_leaderboard_entries(id, order, offset, limit)
                    result["leaderboard_name"] = leaderboard_name
                    return result
                else:
                    cherrypy.response.status = 404
                    return "Leaderboard " + leaderboard_name + " for game  " + game + " not found"
        except KeyError as e:
            cherrypy.response.status = 400
        except Exception as e:
            cherrypy.response.status = 500